<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 订单状态 -->
    <view class="bg-white px-[32rpx] py-[40rpx]">
      <view class="flex items-center justify-center mb-[32rpx]">
        <text class="text-[48rpx] mr-[16rpx]">{{ getStatusIcon(orderDetail.status) }}</text>
        <text class="text-[36rpx] font-bold" :class="getStatusColor(orderDetail.status)">
          {{ getStatusText(orderDetail.status) }}
        </text>
      </view>
      <text class="text-[28rpx] text-gray-600 text-center block">
        {{ getStatusDescription(orderDetail.status) }}
      </text>
    </view>

    <!-- 配送信息 -->
    <view v-if="orderDetail.deliveryInfo" class="bg-white px-[32rpx] py-[32rpx] mt-[20rpx]">
      <text class="text-[32rpx] font-bold text-gray-800 block mb-[24rpx]">配送信息</text>
      
      <!-- 配送地址 -->
      <view class="flex items-start mb-[24rpx]">
        <text class="text-[28rpx] text-gray-600 mr-[16rpx] mt-[4rpx]">📍</text>
        <view class="flex-1">
          <text class="text-[30rpx] font-medium text-gray-800 block mb-[8rpx]">
            {{ orderDetail.deliveryInfo.name }} {{ orderDetail.deliveryInfo.phone }}
          </text>
          <text class="text-[28rpx] text-gray-600">{{ orderDetail.deliveryInfo.address }}</text>
        </view>
      </view>

      <!-- 骑手信息 -->
      <view v-if="orderDetail.rider" class="flex items-center justify-between p-[24rpx] bg-gray-50 rounded-[16rpx]">
        <view class="flex items-center">
          <image 
            :src="orderDetail.rider.avatar || defaultProductImage" 
            class="w-[80rpx] h-[80rpx] rounded-full mr-[24rpx]"
            mode="aspectFill"
          />
          <view>
            <text class="text-[30rpx] font-medium text-gray-800 block mb-[8rpx]">{{ orderDetail.rider.name }}</text>
            <text class="text-[26rpx] text-gray-500">配送员 · 评分{{ orderDetail.rider.rating }}</text>
          </view>
        </view>
        <nut-button 
          type="primary" 
          size="small"
          class="bg-green-500 border-green-500"
          @click="callRider"
        >
          联系骑手
        </nut-button>
      </view>

      <!-- 预计送达时间 -->
      <view v-if="orderDetail.estimatedDeliveryTime" class="mt-[24rpx]">
        <text class="text-[28rpx] text-gray-600">预计送达：{{ orderDetail.estimatedDeliveryTime }}</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="bg-white px-[32rpx] py-[32rpx] mt-[20rpx]">
      <text class="text-[32rpx] font-bold text-gray-800 block mb-[24rpx]">商品信息</text>
      
      <view 
        v-for="item in orderDetail.items" 
        :key="item.id"
        class="flex items-center mb-[24rpx] last:mb-0"
      >
        <image 
          :src="item.image" 
          class="w-[120rpx] h-[120rpx] rounded-[16rpx] object-cover mr-[24rpx]"
          mode="aspectFill"
        />
        <view class="flex-1">
          <text class="text-[30rpx] font-medium text-gray-800 block mb-[8rpx]">{{ item.name }}</text>
          <text class="text-[26rpx] text-gray-500 block mb-[8rpx]">{{ item.description }}</text>
          <text class="text-[26rpx] text-gray-500">x{{ item.quantity }}</text>
        </view>
        <text class="text-[30rpx] font-bold text-gray-800">¥{{ (item.price * item.quantity).toFixed(2) }}</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="bg-white px-[32rpx] py-[32rpx] mt-[20rpx]">
      <text class="text-[32rpx] font-bold text-gray-800 block mb-[24rpx]">订单信息</text>
      
      <view class="space-y-[16rpx]">
        <view class="flex justify-between items-center">
          <text class="text-[28rpx] text-gray-600">订单号</text>
          <text class="text-[28rpx] text-gray-800">{{ orderDetail.orderNo }}</text>
        </view>
        <view class="flex justify-between items-center">
          <text class="text-[28rpx] text-gray-600">下单时间</text>
          <text class="text-[28rpx] text-gray-800">{{ formatDate(orderDetail.createTime) }}</text>
        </view>
        <view class="flex justify-between items-center">
          <text class="text-[28rpx] text-gray-600">支付方式</text>
          <text class="text-[28rpx] text-gray-800">{{ orderDetail.paymentMethod || '在线支付' }}</text>
        </view>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="bg-white px-[32rpx] py-[32rpx] mt-[20rpx]">
      <text class="text-[32rpx] font-bold text-gray-800 block mb-[24rpx]">费用明细</text>
      
      <view class="space-y-[16rpx]">
        <view class="flex justify-between items-center">
          <text class="text-[28rpx] text-gray-600">商品小计</text>
          <text class="text-[28rpx] text-gray-800">¥{{ orderDetail.subtotal.toFixed(2) }}</text>
        </view>
        <view class="flex justify-between items-center">
          <text class="text-[28rpx] text-gray-600">配送费</text>
          <text class="text-[28rpx] text-gray-800">¥{{ orderDetail.deliveryFee.toFixed(2) }}</text>
        </view>
        <view v-if="orderDetail.discount > 0" class="flex justify-between items-center">
          <text class="text-[28rpx] text-gray-600">优惠减免</text>
          <text class="text-[28rpx] text-red-500">-¥{{ orderDetail.discount.toFixed(2) }}</text>
        </view>
        <view class="border-t border-gray-200 pt-[16rpx]">
          <view class="flex justify-between items-center">
            <text class="text-[32rpx] font-bold text-gray-800">实付金额</text>
            <text class="text-[32rpx] font-bold text-red-500">¥{{ orderDetail.totalAmount.toFixed(2) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 配送轨迹 -->
    <view v-if="deliveryTrack.length > 0" class="bg-white px-[32rpx] py-[32rpx] mt-[20rpx]">
      <text class="text-[32rpx] font-bold text-gray-800 block mb-[24rpx]">配送轨迹</text>
      
      <view class="space-y-[24rpx]">
        <view 
          v-for="(track, index) in deliveryTrack" 
          :key="index"
          class="flex items-start"
        >
          <view class="flex flex-col items-center mr-[24rpx]">
            <view 
              class="w-[16rpx] h-[16rpx] rounded-full"
              :class="index === 0 ? 'bg-green-500' : 'bg-gray-300'"
            ></view>
            <view 
              v-if="index < deliveryTrack.length - 1"
              class="w-[2rpx] h-[40rpx] bg-gray-200 mt-[8rpx]"
            ></view>
          </view>
          <view class="flex-1">
            <text class="text-[30rpx] font-medium text-gray-800 block mb-[8rpx]">{{ track.status }}</text>
            <text class="text-[26rpx] text-gray-500">{{ track.time }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-[32rpx] py-[32rpx]">
      <view class="flex items-center space-x-[24rpx]">
        <nut-button 
          v-if="orderDetail.status === 'pending'" 
          type="default" 
          size="large"
          class="flex-1"
          @click="cancelOrder"
        >
          取消订单
        </nut-button>
        <nut-button 
          v-if="orderDetail.status === 'pending'" 
          type="primary" 
          size="large"
          class="flex-1 bg-orange-500 border-orange-500"
          @click="payOrder"
        >
          立即支付
        </nut-button>
        <nut-button 
          v-if="orderDetail.status === 'completed'" 
          type="primary" 
          size="large"
          class="flex-1 bg-orange-500 border-orange-500"
          @click="reorder"
        >
          再来一单
        </nut-button>
      </view>
    </view>

    <!-- 底部安全区域 -->
    <view class="h-[160rpx]"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'

/**
 * 订单详情页面 - 显示订单完整信息和配送状态
 * 性能优化：实时状态更新，配送轨迹实时同步
 */

interface OrderItem {
  id: number
  name: string
  description: string
  price: number
  quantity: number
  image: string
}

interface DeliveryInfo {
  address: string
  phone: string
  name: string
}

interface Rider {
  id: number
  name: string
  phone: string
  rating: number
  avatar: string
}

interface OrderDetail {
  id: number
  orderNo: string
  status: 'pending' | 'preparing' | 'delivering' | 'completed' | 'cancelled'
  items: OrderItem[]
  subtotal: number
  deliveryFee: number
  discount: number
  totalAmount: number
  createTime: string
  deliveryInfo?: DeliveryInfo
  rider?: Rider
  estimatedDeliveryTime?: string
  paymentMethod?: string
}

interface DeliveryTrack {
  status: string
  time: string
}

// 使用Taro导航

// 响应式数据
const defaultProductImage = 'http://www.dzgktf.com/templets/default/images/wtyt.jpg'

// 订单详情数据
const orderDetail = ref<OrderDetail>({
  id: 1,
  orderNo: 'MT202312230001',
  status: 'delivering',
  subtotal: 50,
  deliveryFee: 8,
  discount: 0,
  totalAmount: 58,
  createTime: '2023-12-23 14:30:00',
  items: [
    {
      id: 1,
      name: '珍珠奶茶',
      description: '经典珍珠奶茶，香浓顺滑',
      price: 18,
      quantity: 2,
      image: defaultProductImage
    },
    {
      id: 2,
      name: '芒果布丁奶茶',
      description: '新鲜芒果配布丁',
      price: 22,
      quantity: 1,
      image: defaultProductImage
    }
  ],
  deliveryInfo: {
    address: '北京市朝阳区三里屯SOHO A座1202',
    phone: '138****8888',
    name: '张先生'
  },
  rider: {
    id: 1,
    name: '李师傅',
    phone: '139****9999',
    rating: 4.8,
    avatar: defaultProductImage
  },
  estimatedDeliveryTime: '15:00',
  paymentMethod: '微信支付'
})

// 配送轨迹
const deliveryTrack = ref<DeliveryTrack[]>([
  { status: '骑手正在配送中', time: '14:45' },
  { status: '商家已出餐，骑手已取餐', time: '14:35' },
  { status: '商家正在制作中', time: '14:32' },
  { status: '订单已确认，等待商家接单', time: '14:30' }
])

// 方法
const getStatusIcon = (status: OrderDetail['status']) => {
  const iconMap = {
    pending: '💰',
    preparing: '☕',
    delivering: '🚚',
    completed: '✅',
    cancelled: '❌'
  }
  return iconMap[status]
}

const getStatusText = (status: OrderDetail['status']) => {
  const textMap = {
    pending: '待付款',
    preparing: '制作中',
    delivering: '配送中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status]
}

const getStatusColor = (status: OrderDetail['status']) => {
  const colorMap = {
    pending: 'text-orange-600',
    preparing: 'text-blue-600',
    delivering: 'text-green-600',
    completed: 'text-gray-600',
    cancelled: 'text-red-600'
  }
  return colorMap[status]
}

const getStatusDescription = (status: OrderDetail['status']) => {
  const descriptionMap = {
    pending: '请尽快完成支付，超时将自动取消订单',
    preparing: '商家正在用心制作您的美味奶茶',
    delivering: '骑手正在马不停蹄地为您配送',
    completed: '订单已完成，期待您的再次光临',
    cancelled: '订单已取消'
  }
  return descriptionMap[status]
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const callRider = () => {
  console.log('联系骑手:', orderDetail.value.rider?.phone)
  // 实际项目中会调用拨号功能
}

const cancelOrder = () => {
  console.log('取消订单:', orderDetail.value.orderNo)
  orderDetail.value.status = 'cancelled'
}

const payOrder = () => {
  console.log('支付订单:', orderDetail.value.orderNo)
  // 跳转到支付页面
}

const reorder = () => {
  console.log('再来一单:', orderDetail.value.orderNo)
  // 将订单商品重新加入购物车
}

// 生命周期
onMounted(() => {
  console.log('订单详情页面加载完成')
  // 开始订单状态实时更新
  startOrderStatusUpdate()
})

const startOrderStatusUpdate = () => {
  console.log('开始订单状态更新')
  // 实际项目中会开启轮询或WebSocket监听
}
</script>

<style lang="scss" scoped>
.space-y-\[16rpx\] > view:not(:first-child) {
  margin-top: 16rpx;
}

.space-y-\[24rpx\] > view:not(:first-child) {
  margin-top: 24rpx;
}

.space-x-\[24rpx\] > view:not(:first-child) {
  margin-left: 24rpx;
}

.last\:mb-0:last-child {
  margin-bottom: 0;
}
</style> 